In [ ]:
%autosave 0

I/O

File I/O

Similar to fopen() in C, open() close() read() write() seek() are supported, not only these function calls, readline() readlines() are also supported. File object can be treated as a iterator, may be it is more common.

print() function can write to file with file= option. open(), close(), readline(), print() will be most commonly used function for text I/O.

readline() function returns the 1 line data include \n, and returns '' (0 length string) for EOF (End Of File).


In [ ]:
fd = open('README.md', 'r')
print(fd.readline(), end='')   # \n is included in input string

for s in fd:      # file object(descriptor) is iterable, and can be used in for loop
    print(s.strip())    # strip() removes extra space and \n
    # print(s.split())  # convert string to List

Data conversion

int() function convert string or float to integer, str() convert to string, float() convert to float. map(func, iterable-object) apply function to iterable-object and returns iterable object.


In [ ]:
s = '100'
print(int(s)+1)

s = '1 2 3'
for i in map(int, s.split()):
    print(i)

In [ ]:
s = '1 2 3 4'
x = list(map(int, s.split()))
print(x)

y = list()
for i in s.split():  # ['1', '2', '3', '4']
    y.append(int(i))
    
print(y)

Standard In, Standard Out and Standard Error

sys.stdin, sys.stdout and sys.stderr are file descriptors which are already opened for application programs. stardard-in is assinged to keyboard, standard-out and standard-error are assinged to display as a default. These assigned can be overrided when executing the program from shell.

$ program_name <input_file
$ program_name >output_file
$ program_name <input_file >output_file
$ program_name 2>error_file

In [ ]:
# need to import sys module to use standard I/O file descriptor
import sys
print('input somthing: ')

# jupyter does not handle stdin ?
# sys.stdin is used as a file-descriptor
s = sys.stdin.readline()
print(s.split())   # convert input to List